    package com.dingwen.spsest.filter;
    
    import com.dingwen.spsest.controller.CodeController;
    import com.dingwen.spsest.exception.ValidateCodeException;
    import com.dingwen.spsest.handler.MyAuthenticationFailureHandler;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpMethod;
    import org.springframework.security.core.AuthenticationException;
    import org.springframework.stereotype.Component;
    import org.springframework.util.StringUtils;
    import org.springframework.web.filter.GenericFilterBean;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.Optional;
    
    /**
     * 验证代码过滤
     * 验证码验证过滤器
     *
     * @author dingwen
     * 2021.05.19 17:28
     * @date 2021/05/19
     */
    @Component
    public class VerifyCodeFilter extends GenericFilterBean {
        private final MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    
        @Autowired
        VerifyCodeFilter(MyAuthenticationFailureHandler myAuthenticationFailureHandler) {
            this.myAuthenticationFailureHandler = myAuthenticationFailureHandler;
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            String defaultFilterProcessUrl = "/login";
    
            try {
                if (HttpMethod.POST.name().equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
                    // 验证码验证
                    String code = request.getParameter("code");
                    String genCaptcha = (String) request.getSession().getAttribute(CodeController.CODE_KEY);
                    Optional.ofNullable(code).orElseThrow(() -> new ValidateCodeException("验证码不能为空!"));
                    if (!genCaptcha.toLowerCase().equals(code.toLowerCase())) {
                        throw new ValidateCodeException("验证码错误");
                    }
                }
            } catch (AuthenticationException authenticationException) {
                // 捕获异常交给失败处理器处理
                myAuthenticationFailureHandler.onAuthenticationFailure(request, response, authenticationException);
            }
            chain.doFilter(request, response);
        }
    }
